package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.dto.ItemDTO;
import com.hmall.common.msg.UpOrDownMsg;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private  RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper mapper;

    /**
     * 商品上架、下架---商品管理
     * @param id 商品id
     * @param status 商品状态（1，正常， 2 下架， 3 删除）
     */
//    @Transactional
//    @Override
//    public void updateStatus(Long id, Integer status) {
//        this.update().set("status",status).eq("id",id).update();
//    }
    @Override
    public void updateDownOrUp(Long id, Integer status) {
        //1.写数据库
        //4.wrappers构建条件
        this.update(Wrappers.<Item>lambdaUpdate().set(Item::getStatus,status).eq(Item::getId,id));
        //2.发消息给rabbitmq
//        ItemDTO itemDTO = new ItemDTO();
//        itemDTO.setId(id);
//        itemDTO.setStatus(status);
//        rabbitTemplate.convertAndSend("item100.upordown",status == 1 ? "key.up100" : "key.down100",itemDTO);
        Item item = this.getById(id);
        ItemDTO itemDTO = new ItemDTO();
        BeanUtils.copyProperties(item,itemDTO);
        UpOrDownMsg upOrDownMsg = new UpOrDownMsg();
        upOrDownMsg.setStatus(status);
        upOrDownMsg.setItemDTO(itemDTO);
        try {
            rabbitTemplate.convertAndSend("item100.upordown2","key",mapper.writeValueAsString(upOrDownMsg));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 库存扣减业务
     * @param itemId
     * @param num
     */
    @Transactional
    @Override
    public void deductStock(Long itemId, Integer num) {
        try {
            // update tb_item set stock = stock - #{num} where id = #{itemId}
            if(num < 0){
                update().setSql("stock = stock - " + Math.abs(num)).eq("id", itemId).update();
            }else{
                update().setSql("stock = stock + " + Math.abs(num)).eq("id", itemId).update();
            }

        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
    }
}
